package br.com.mensageiro.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.stereotype.Repository;

@Repository("arquivoUtils")
public class ArquivoUtils {
	public byte[] fileTobyte(File file) {
		InputStream stream;
		try {
			stream = new FileInputStream(file);

			byte[] bytes = new byte[(int) file.length()];
			int offset = 0;
			int numRead = 0;

			while (offset < bytes.length && (numRead = stream.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}

			return bytes;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public File byteTofile(byte[] bytesArquivo, String nomeArquivo) {
		File file = null;

		try {
			byte[] bytes = bytesArquivo;
			String nome = nomeArquivo;

			// Converte o array de bytes em file
			file = new File("C://Users//Robson//Documents//" + nome);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bytes);
			fos.close();

			return file;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
